import java.util.Arrays;

public class TestHeap {
    private int[] elem;
    private int usedSize;
    public TestHeap() {
        this.elem = new int[10];
    }
    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    public void createHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0 ; parent--) {
            shifDown(parent,usedSize);
        }
    }

    private void shifDown(int parent, int usedSize) {
        int child = parent * 2 + 1;
        while (child < usedSize) {
            if (child + 1 < usedSize && elem[child] < elem[child + 1]) {
                child++;
            }
            if (elem[child] > elem[parent]) {
                swap(parent,child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    private void swap (int parent, int child) {
        int tmp = elem[parent];
        elem[parent] = elem[child];
        elem[child] = tmp;
    }

    public void offer (int val) {
        if (isFull()) {
            this.elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize] = val;
        shifUp(usedSize);
        usedSize++;
    }
    public int pop () {
        if (isEmpty()) {
            return -1;
        }
        int oldValue = elem[0];
        swap(0,usedSize - 1);
        usedSize--;
        shifDown(0,usedSize);
        return oldValue;
    }
    private boolean isFull() {
        return usedSize == elem.length;
    }

    public void shifUp (int child) {
        int parent = (child - 1) / 2;
        while (child > 0) {
            if (elem[child] > elem[parent]) {
                swap(parent,child);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }
    public int peek() {
        if (isEmpty()) {
            return -1;
        }
        return elem[0];
    }
    public void heapSort() {
        int end = usedSize - 1;
        while (end > 0) {
            swap(0,end);
            shifDown(0,end);
            end--;
        }
    }
}


